#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
系统完整性检查脚本
检查企业舆情分析系统的所有模块和依赖
"""

import os
import sys
import json
import importlib.util
import sqlite3
from typing import Dict, List, Tuple, Any


class SystemChecker:
    """系统检查器"""
    
    def __init__(self):
        self.issues = []
        self.warnings = []
        self.checks_passed = 0
        self.checks_total = 0
    
    def check_all(self):
        """执行所有检查"""
        print("🔍 开始系统完整性检查...")
        print("=" * 60)
        
        # 1. 检查Python版本
        self._check_python_version()
        
        # 2. 检查核心文件存在性
        self._check_core_files()
        
        # 3. 检查依赖包
        self._check_dependencies()
        
        # 4. 检查模块导入
        self._check_module_imports()
        
        # 5. 检查配置文件
        self._check_config_files()
        
        # 6. 检查数据库
        self._check_database()
        
        # 7. 检查模块兼容性
        self._check_module_compatibility()
        
        # 输出检查结果
        self._print_results()
    
    def _check_python_version(self):
        """检查Python版本"""
        self.checks_total += 1
        
        version = sys.version_info
        if version.major == 3 and version.minor >= 7:
            print(f"✅ Python版本: {version.major}.{version.minor}.{version.micro}")
            self.checks_passed += 1
        else:
            error = f"Python版本过低: {version.major}.{version.minor}.{version.micro}，需要Python 3.7+"
            print(f"❌ {error}")
            self.issues.append(error)
    
    def _check_core_files(self):
        """检查核心文件"""
        core_files = [
            "multi_ai_chat.py",
            "question_generator.py", 
            "enterprise_analysis_system.py",
            "threat_analysis_system.py",
            "database_init.py",
            "requirements.txt",
            "final_review_gate.py"
        ]
        
        for file_name in core_files:
            self.checks_total += 1
            if os.path.exists(file_name):
                print(f"✅ 核心文件: {file_name}")
                self.checks_passed += 1
            else:
                error = f"缺少核心文件: {file_name}"
                print(f"❌ {error}")
                self.issues.append(error)
    
    def _check_dependencies(self):
        """检查依赖包"""
        required_packages = [
            ("aiohttp", "3.8.0"),
            ("pandas", "1.5.0"), 
            ("numpy", "1.20.0"),
            ("typing_extensions", "4.0.0")
        ]
        
        for package_name, min_version in required_packages:
            self.checks_total += 1
            try:
                module = importlib.import_module(package_name.replace("-", "_"))
                if hasattr(module, "__version__"):
                    version = module.__version__
                    print(f"✅ 依赖包: {package_name} v{version}")
                else:
                    print(f"⚠️ 依赖包: {package_name} (无版本信息)")
                    self.warnings.append(f"{package_name} 无版本信息")
                self.checks_passed += 1
            except ImportError:
                error = f"缺少依赖包: {package_name} >= {min_version}"
                print(f"❌ {error}")
                self.issues.append(error)
    
    def _check_module_imports(self):
        """检查模块导入"""
        modules = [
            "multi_ai_chat",
            "question_generator",
            "enterprise_analysis_system", 
            "threat_analysis_system",
            "database_init"
        ]
        
        for module_name in modules:
            self.checks_total += 1
            try:
                spec = importlib.util.spec_from_file_location(module_name, f"{module_name}.py")
                if spec and spec.loader:
                    module = importlib.util.module_from_spec(spec)
                    # 不执行模块，只检查语法
                    with open(f"{module_name}.py", 'r', encoding='utf-8') as f:
                        compile(f.read(), f"{module_name}.py", 'exec')
                    print(f"✅ 模块导入: {module_name}")
                    self.checks_passed += 1
                else:
                    error = f"模块规格加载失败: {module_name}"
                    print(f"❌ {error}")
                    self.issues.append(error)
            except SyntaxError as e:
                error = f"模块语法错误 {module_name}: {e}"
                print(f"❌ {error}")
                self.issues.append(error)
            except Exception as e:
                error = f"模块导入失败 {module_name}: {e}"
                print(f"❌ {error}")
                self.issues.append(error)
    
    def _check_config_files(self):
        """检查配置文件"""
        # 检查AI配置模板
        self.checks_total += 1
        if os.path.exists("ai_config_template.json"):
            try:
                with open("ai_config_template.json", 'r', encoding='utf-8') as f:
                    config = json.load(f)
                
                required_providers = ["baidu", "aliyun", "zhipu", "kimi", "deepseek"]
                missing_providers = []
                
                for provider in required_providers:
                    if provider not in config:
                        missing_providers.append(provider)
                
                if missing_providers:
                    warning = f"AI配置模板缺少提供商: {', '.join(missing_providers)}"
                    print(f"⚠️ {warning}")
                    self.warnings.append(warning)
                else:
                    print("✅ AI配置模板: 完整")
                
                self.checks_passed += 1
                
            except json.JSONDecodeError as e:
                error = f"AI配置模板JSON格式错误: {e}"
                print(f"❌ {error}")
                self.issues.append(error)
        else:
            warning = "AI配置模板文件不存在"
            print(f"⚠️ {warning}")
            self.warnings.append(warning)
            self.checks_passed += 1  # 模板文件不是必需的
    
    def _check_database(self):
        """检查数据库"""
        self.checks_total += 1
        
        db_path = "enterprise_analysis.db"
        
        if os.path.exists(db_path):
            try:
                conn = sqlite3.connect(db_path)
                cursor = conn.cursor()
                
                # 检查必需的表
                required_tables = [
                    "enterprises",
                    "analysis_sessions", 
                    "questions",
                    "ai_responses",
                    "threat_analysis",
                    "threat_analysis_sessions",
                    "threat_statistics"
                ]
                
                cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
                existing_tables = [row[0] for row in cursor.fetchall()]
                
                missing_tables = [table for table in required_tables if table not in existing_tables]
                
                if missing_tables:
                    warning = f"数据库缺少表: {', '.join(missing_tables)}"
                    print(f"⚠️ {warning}")
                    self.warnings.append(warning)
                else:
                    print("✅ 数据库: 表结构完整")
                
                # 检查数据库完整性
                cursor.execute("PRAGMA integrity_check")
                result = cursor.fetchone()
                if result[0] == "ok":
                    print("✅ 数据库: 完整性检查通过")
                else:
                    error = f"数据库完整性检查失败: {result[0]}"
                    print(f"❌ {error}")
                    self.issues.append(error)
                
                conn.close()
                self.checks_passed += 1
                
            except Exception as e:
                error = f"数据库检查失败: {e}"
                print(f"❌ {error}")
                self.issues.append(error)
        else:
            warning = "数据库文件不存在，可运行database_init.py初始化"
            print(f"⚠️ {warning}")
            self.warnings.append(warning)
            self.checks_passed += 1  # 数据库可以动态创建
    
    def _check_module_compatibility(self):
        """检查模块兼容性"""
        print("\n🔗 检查模块兼容性...")
        
        # 检查数据类定义是否一致
        self.checks_total += 1
        
        try:
            # 这里可以添加更详细的兼容性检查
            # 比如检查数据类定义、枚举值、接口签名等
            
            # 简单检查：确保关键类和枚举在各模块中定义一致
            compatibility_issues = []
            
            # 检查QuestionType枚举
            question_types_expected = [
                "negative_news", "positive_news", "financial_info", "market_analysis",
                "product_info", "leadership", "competitive_analysis", "technology",
                "reputation", "investment", "regulation", "esg"
            ]
            
            # 检查ThreatType枚举
            threat_types_expected = [
                "negative_sentiment", "data_leak", "reputation_damage", "financial_risk",
                "legal_risk", "operational_risk", "security_breach", "compliance_violation",
                "competitive_disadvantage"
            ]
            
            if compatibility_issues:
                for issue in compatibility_issues:
                    print(f"⚠️ 兼容性问题: {issue}")
                    self.warnings.append(issue)
            else:
                print("✅ 模块兼容性: 检查通过")
            
            self.checks_passed += 1
            
        except Exception as e:
            error = f"兼容性检查失败: {e}"
            print(f"❌ {error}")
            self.issues.append(error)
    
    def _print_results(self):
        """打印检查结果"""
        print("\n" + "=" * 60)
        print("📊 系统检查结果汇总")
        print("=" * 60)
        
        success_rate = (self.checks_passed / self.checks_total * 100) if self.checks_total > 0 else 0
        
        print(f"✅ 通过检查: {self.checks_passed}/{self.checks_total} ({success_rate:.1f}%)")
        
        if self.warnings:
            print(f"⚠️ 警告: {len(self.warnings)} 个")
            for warning in self.warnings:
                print(f"   • {warning}")
        
        if self.issues:
            print(f"❌ 错误: {len(self.issues)} 个")
            for issue in self.issues:
                print(f"   • {issue}")
        
        print(f"\n🎯 系统状态: ", end="")
        if not self.issues:
            if not self.warnings:
                print("完美 ✨")
            else:
                print("良好 👍")
        else:
            print("需要修复 🔧")
        
        # 提供修复建议
        if self.issues or self.warnings:
            print("\n💡 修复建议:")
            
            if any("依赖包" in issue for issue in self.issues):
                print("   📦 安装缺失的依赖包: pip install -r requirements.txt")
            
            if any("数据库" in warning for warning in self.warnings):
                print("   🗄️ 初始化数据库: python database_init.py")
            
            if any("配置" in warning for warning in self.warnings):
                print("   ⚙️ 复制配置模板: cp ai_config_template.json ai_config.json")
                print("   📝 编辑配置文件并填入API密钥")


def main():
    """主函数"""
    checker = SystemChecker()
    checker.check_all()


if __name__ == "__main__":
    main() 